import pandas as pd
import numpy as np

# 生成模拟数据
np.random.seed(42)
data = []

# 创建3个款号的模拟数据
for spu in ['A001', 'A002', 'B001']:
    cart_total = np.random.randint(500, 2000)
    new_sale = np.random.randint(20, 100)

    # 生成30天的动态数据
    for day in range(1, 31):
        base_sale = 100 * np.exp(-0.05 * day)
        sale_qty = max(0, int(base_sale + np.random.normal(0, 10)))

        data.append({
            'spu_code': spu,
            'sum_cart_total': cart_total,
            'new_sale_qty': new_sale,
            'days_since_launch': day,
            'sale_qty': sale_qty
        })

# 创建DataFrame并保存
df = pd.DataFrame(data)
df.to_excel("sales_data.xlsx", index=False)
print("模拟数据已生成并保存为 sales_data.xlsx")

import pandas as pd
import joblib
import lightgbm as lgb
from sklearn.model_selection import train_test_split

def train_lightgbm_models(data_file):
    """使用LightGBM训练所有款号的模型并保存"""
    # 加载数据
    df = pd.read_excel(data_file)

    # 存储所有训练好的模型
    models = {}

    # 按款号分组训练
    for spu, group in df.groupby('spu_code'):
        # 准备训练数据
        X = group[['sum_cart_total', 'new_sale_qty', 'days_since_launch']]
        y = group['sale_qty']

        # 划分训练集和验证集
        X_train, X_val, y_train, y_val = train_test_split(
            X, y, test_size=0.2, random_state=42
        )

        # 创建LightGBM数据集
        train_data = lgb.Dataset(X_train, label=y_train)
        val_data = lgb.Dataset(X_val, label=y_val, reference=train_data)

        # 设置模型参数
        params = {
            'objective': 'regression',
            'metric': 'rmse',
            'learning_rate': 0.05,
            'num_leaves': 31,
            'max_depth': -1,
            'min_data_in_leaf': 20,
            'feature_fraction': 0.8,
            'bagging_fraction': 0.8,
            'bagging_freq': 5,
            'verbose': -1,
            'seed': 42
        }

        # 训练模型
        model = lgb.train(
            params,
            train_data,
            num_boost_round=1000,
            valid_sets=[val_data],
            callbacks=[
                lgb.early_stopping(stopping_rounds=50, verbose=False),
                lgb.log_evaluation(period=100)
            ]
        )

        # 存储模型
        models[spu] = model
        print(f"款号 {spu} LightGBM模型训练完成，使用数据量: {len(group)}")

    # 保存所有模型
    joblib.dump(models, 'lightgbm_models.pkl')
    print("所有模型已保存为 lightgbm_models.pkl")

    return models


if __name__ == "__main__":
    models = train_lightgbm_models("sales_data.xlsx")
